package YAVMM::Settings::MongoDB;
use Moose;

with 'YAVMM::Settings';

use TryCatch;

use YAVMM::Types;
use YAVMM::Error::Parameter;
use YAVMM::Error::ParseError;
use YAVMM::Error::DBError;

with 'YAVMM::Role::MongoDB';

#use MongoDB;

our $VERSION = '0.01';

has '+collection' => (
    default    => 'yavmm_settings',
);

sub add {
    my $self = shift;
    my %setting = @_;

    if (not $self->_coll->update(
	    { section => $setting{section}, key => $setting{key} },
	    { '$set' => { %setting } },
	    { 'upsert' => 1 } )
    ) {
	my $err = $self->_db->last_error();
	# This should almost certainly be set but, just to be sure ...
	if ($err->{err}) {
	    die YAVMM::Error::DBError->(
		error => "Unable to add setting: $err->{err}",
	    );
	}
    }
}

sub get {
    my $self    = shift;
    my $section = shift;
    my $key     = shift;

    if (not $section or not $key) {
	die YAVMM::Error::Parameter->new(
	    error => "Section or key missing"
	);
    }

    my $obj = $self->_coll->find_one(
	{
	    'section' => $section,
	    'key'     => $key,
	},
	{
	    'value' => 1
	}
    );

    if (defined $obj) {
	return $obj->{value};
    }
    else {
	return undef;
    }
}

sub set {
    my $self    = shift;
    my $section = shift;
    my $key     = shift;
    my $value   = shift;

    if (not $self->_coll->update(
	    { section => $section, key => $key },
	    { '$set' => { section => $section, key => $key, value => $value } },
	    { 'upsert' => 1 } )
    ) {
	my $err = $self->_db->last_error();
	# This should almost certainly be set but, just to be sure ...
	if ($err->{err}) {
	    die YAVMM::Error::DBError->(
		error => "Unable to set setting: $err->{err}",
	    );
	}
    }
}

sub unset {
    my $self    = shift;
    my $section = shift;
    my $key     = shift;

    $self->set($section, $key, undef);
}

sub commit {
    # noop
}

sub reread {
    # noop
}

1;

__END__
